/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.elcom.emocbc.blacklist;

import com.elcom.config.ModuleConfig;
import com.elcom.util.Constant;
import com.elcom.util.app.IApplication;
import java.io.File;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import org.apache.log4j.PropertyConfigurator;
import org.jconfig.Configuration;
import org.jconfig.ConfigurationManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author GiangLT
 */
public class Main implements IApplication {

    private final static Logger logger = LoggerFactory.getLogger(Main.class);
    public static AtomicInteger seq = new AtomicInteger(1);
    public static ScheduledExecutorService executorService;
    private BlacklistFileHandler blacklistFileHandler;

    public static void main(String[] args) {
        try {
            Main main = new Main();
            main.start(args);
        } catch (Throwable ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void stop(String[] strings) throws Throwable {

        executorService.shutdown(); // Disable new tasks from being submitted
        try {
            // Wait a while for existing tasks to terminate
            if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
                executorService.shutdownNow(); // Cancel currently executing tasks
                // Wait a while for tasks to respond to being cancelled
                if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
                    logger.error("Executor did not terminate");
                }
            }
        } catch (InterruptedException ie) {
            // (Re-)Cancel if current thread also interrupted
            executorService.shutdownNow();
//            // Preserve interrupt status
//            Thread.currentThread().interrupt();
        }
    }

    @Override
    public void start(String[] strings) throws Throwable {
        try {
            File file = new File(Constant.LOG_FOLDER);
            if (!file.exists()) {
                file.mkdirs();
            }

            file = new File(Constant.CONFIG_FOLDER);
            if (!file.exists()) {
                file.mkdirs();
            }

            PropertyConfigurator.configureAndWatch(Constant.CONFIG_FOLDER + Constant.MODULE_NAME + "-log4j.props");

            //Chay reload config
            ModuleConfig jConfig = new ModuleConfig();
            try {
                jConfig.reloadConfig(Constant.CONFIG_FOLDER, Constant.CONFIG_FILE_NAME);
            } catch (Exception ex) {
                logger.error("", ex);
            }

            Configuration configuration = ConfigurationManager.getConfiguration(Constant.SYS_CONFIG_NAME);
            String filePath = configuration.getProperty("blacklistFile", "", "general");
            File blacklistFile = new File(filePath);
            blacklistFileHandler = new BlacklistFileHandler(blacklistFile);

            executorService = Executors.newScheduledThreadPool(5);
            BlacklistParser blacklistParser = new BlacklistParser(blacklistFileHandler);

            Long initialDelay = configuration.getLongProperty("initialDelayMs", 1000, "executor");
            Long period = configuration.getLongProperty("periodMs", 300000, "executor");
            executorService.scheduleAtFixedRate(blacklistParser, initialDelay, period, TimeUnit.MILLISECONDS);
        } catch (Exception ex) {
            logger.error("", ex);
        }
    }

    @Override
    public void restart(String[] strings) throws Throwable {
        stop(strings);
        start(strings);
    }

    @Override
    public String get_info(String[] strings) throws Throwable {
        return "";
    }

    @Override
    public void reload_config(String[] strings) throws Throwable {
    }
}
